<?php
/*
 * Copyright (c) 2011 Todd Brady
 *
 * PS3Theatre is freely distributable under the terms of the MIT license.
 * For details, see the MIT-Liscence web site: http://www.opensource.org/licenses/mit-license.php 
 */
 	include("includes/db_connect.php");
	
	$id = $_GET['id'];
	$action = $_GET['action'];
	$tmdbId = "";
	$title = "";
	$overview = "";
	$rating = "";
	$certification = "";
	$releasedDate = "";
	$runtime = "";
	$budget = "";
	$revenue = "";
	$director = "";
	$discFlagId = "";
	$audioFlagId = "";
	$isWatched = "";
	
	//fill 2 dropdowns
	$audioFlagQuery =  "SELECT id,label from tbl_audio_flags ORDER BY label";
	$discFlagQuery = "SELECT id,label from tbl_disc_flags ORDER BY label";
	$audioFlags=mysql_query($audioFlagQuery) or die(mysql_error());
	$discFlags=mysql_query($discFlagQuery) or die(mysql_error());
	
	//if action = edit we need to fill out form
	if($action == 'Edit'){
		$movieQuery = "SELECT id, tmdb_id, title, overview, rating, certification, released_date, runtime, budget, revenue, director, disc_flag_id, audio_flag_id, is_watched from tbl_movies where id=".$id;
		$movie=mysql_query($movieQuery) or die(mysql_error());
		$movieRow = mysql_fetch_array($movie);
		$tmdbId = $movieRow['tmdb_id'];
		$title = $movieRow['title'];
		$overview = $movieRow['overview'];
		$rating = $movieRow['rating'];
		$certification = $movieRow['certification'];
		$releasedDate = $movieRow['released_date'];
		$runtime = $movieRow['runtime'];
		$budget = $movieRow['budget'];
		$revenue = $movieRow['revenue'];
		$director = $movieRow['director'];
		$discFlagId = $movieRow['disc_flag_id'];
		$audioFlagId = $movieRow['audio_flag_id'];
		$isWatched = $movieRow['is_watched'];
	
	//if action is delete, just delete and redirect
	}else if($action == 'Del' && $id != ''){
		$deleteQuery = "DELETE from tbl_movies WHERE id=$id";
		$delete=mysql_query($deleteQuery);
		$message = "Movie sucessfully deleted.";
		
		//redirect to movie setup with message
		header("Location: movies-setup.php?message=".$message);
	}

	if(isset($_POST['movieId']))
	{
		$id = $_POST['movieId'];
		$tmdbId = $_POST['tmdbId'];
		$title = $_POST['title'];
		$overview = $_POST['overview'];
		$rating = $_POST['rating'];
		$certification = $_POST['certification'];
		$releasedDate = $_POST['releasedDate'];
		$runtime = $_POST['runtime'];
		$budget = $_POST['budget'];
		$revenue = $_POST['revenue'];
		$director = $_POST['director'];
		$discFlagId = $_POST['discFlagId'];
		$audioFlagId = $_POST['audioFlagId'];
		if($_POST['isWatched'] == 'Y'){
			$isWatched = 'Y';
		}else{
			$isWatched = 'N';
		}
		$message = "";
				
		//insert
		if($id == ''){
			//DO NOTHING FOR NOW, NOT IMPLEMENTED
//			$insertQuery = "insert into tbl_movies (extension,is_active) values ('$extension','$isActive')";
//			$insert=mysql_query($insertQuery);
//			$message = "Movie file extension successfully created.";
		}
		//update
		else{
			$updateQuery = sprintf("update tbl_movies set tmdb_id = '%s', title = '%s', overview = '%s', rating = '%s', certification = '%s', released_date = '%s', runtime = '%s', budget = '%s', revenue = '%s', director = '%s', disc_flag_id='%s', audio_flag_id='%s', is_watched='%s' where id=%s",
			mysql_real_escape_string($tmdbId),
			mysql_real_escape_string($title),
			mysql_real_escape_string($overview),
			mysql_real_escape_string($rating),
			mysql_real_escape_string($certification),
			mysql_real_escape_string($releasedDate),
			mysql_real_escape_string($runtime),
			mysql_real_escape_string($budget),
			mysql_real_escape_string($revenue),
			mysql_real_escape_string($director),
			mysql_real_escape_string($discFlagId),
			mysql_real_escape_string($audioFlagId),
			mysql_real_escape_string($isWatched),
			mysql_real_escape_string($id));
			
			$update=mysql_query($updateQuery) or die('error while trying to update: '.mysql_error());
			$message = "Movie successfully updated.";
		}
	
		//redirect to movie setup with message
		header("Location: movies-setup.php?message=".$message);
	}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<LINK href="../css/main.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="../js/jQuery.js"></script>
<script type="text/javascript" src="../js/simpleModal.js"></script>
<script>
String.prototype.beginsWith = function(t, i) { if (i==false) { return
(t == this.substring(0, t.length)); } else { return (t.toLowerCase()
== this.substring(0, t.length).toLowerCase()); } } 

function scrapeMovieByTitle(){
	confirmWindow('Scanning Movies','<center>Scanning...</center>', 95, 250, false);

	$.ajax({
			url: '../scripts/movieScraper.php?action=scrapeMovieByDBTitleJson&movieId='+$('#id').val()+'&movieTitle='+$('#title').val(),
			type: 'get',
			success: function(data) {
				var resp = jQuery.trim(data);
				if(resp.beginsWith("{\"title\"", true) == true){
					$.modal.close();
				
					//fill fields
					fillFieldsFromJson(resp);	
					
				}else if(resp.beginsWith("There are multiple", true) == true){
					updateConfirm('Multiple Results Returned',resp, 400, 500, true);			

				}else if(resp == 'no results') {
					$.modal.close();
					alert('no results found');

				}else{
					$.modal.close();
					alert('error in scrapeMovieTitle(): '+resp);

				}
			},
			error: function(data) {
				$.modal.close();
	  			alert('Error selecting movie...');
			}
	});
}

function selectDup(movieId, tmdbId){
	$.modal.close();
	$.ajax({
			url: '../scripts/movieScraper.php?action=duplicateSelectedJson&movieId='+movieId+'&tmdbId='+tmdbId,
			type: 'get',
			success: function(data) {
				var resp = jQuery.trim(data);

				if(resp.beginsWith("{\"title\"", true) == true){
					//fill fields
					fillFieldsFromJson(resp);	
					
				}else{
					alert('error: '+resp);
				}
			},
			error: function(data) {
				$.modal.close();
	  			alert('Error selecting movie...');
			}
	});
}


function fillFieldsFromJson(respText){
	var json = jQuery.parseJSON(respText);
	
	$('#title').val(json.title);
	$('#tmdbId').val(json.tmdbId);
	$('#overview').val(json.overview);
	$('#rating').val(json.rating);
	$('#certification').val(json.certification);
	$('#releasedDate').val(json.releasedDate);
	$('#runtime').val(json.runtime);
	$('#budget').val(json.budget);
	$('#revenue').val(json.revenue);
	$('#director').val(json.director);
}

function confirmWindow(title,message, height, width, scrollVar) {
	var newStyle = 'height: '+(height-54)+'px;width: '+(width-12)+'px;';

	if(scrollVar){
		newStyle += ' overflow:scroll;';
	}
	
	$('div.message').attr('style',newStyle);
	$('div.header').html('<span>'+title+'</span>');
	
	$('#confirm').modal({
		closeHTML: "<a href='#' title='Close' class='modal-close'>x</a>",
		autoPosition: 'true',
		overlayId: 'confirm-overlay',
		containerId: 'confirm-container', 
		onShow: function (dialog) {
			var modal = this;
			modal.update(height,width);

			$('.message', dialog.data[0]).append(message);

//				modal.close(); // or $.modal.close();
		}
	});
}

function updateConfirm(title,message, height, width, scrollVar) {
	var newStyle = 'height: '+(height-54)+'px;width: '+(width-12)+'px;';

	if(scrollVar){
		newStyle += ' overflow:scroll;';
	}
	
	$('div.message').attr('style',newStyle);
	$('div.header').html('<span>'+title+'</span>');
	
	$.modal.update(height,width);
	$('div.message').html(message);
}
</script>
</head>
<body>
<h4>Movie <?php echo $action;?></h4>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"]; ?>">
<input name="movieId" type="hidden" id="movieId" value="<?php echo $id;?>" />
<table cellpadding="2" class="rowmajor">
 <tbody>
   <tr>
     <th class="vt"><div align="left">Title:</div></th>
     <td><input name="title" type="text" id="title" size="50" maxlength="512" value="<?php echo $title;?>"/></td>
     <td>&nbsp;</td>
   </tr>
   <tr>
     <th class="vt"><div align="left">Rescan:</div></th>
     <td><input type="button" name="rescanBtn" value="Rescan by Movie Title" onclick="javascript:scrapeMovieByTitle();"/></td>
     <td>Click this if you want themoviedb.org to look for movie info and fill it in. </td>
   </tr>
   <tr>
     <th class="vt"><div align="left">Movie DB Id:</div></th>
     <td><input name="tmdbId" type="text" id="tmdbId" size="20" maxlength="20"  value="<?php echo $tmdbId;?>"/></td>
     <td>id of movie on themoviedb.org, if you don't know what this is leave it alone. </td>
   </tr>
   <tr>
     <th class="vt"><div align="left">Overview:</div></th>
     <td><label>
       <textarea name="overview" cols="50" rows="4" id="overview"><?php echo $overview;?></textarea>
     </label></td>
     <td>&nbsp;</td>
   </tr>
   <tr>
     <th class="vt"><div align="left">Rating:</div></th>
     <td><label>
       <input name="rating" type="text" id="rating" size="5" maxlength="5"  value="<?php echo $rating;?>"/>
     </label></td>
     <td>&nbsp;</td>
   </tr>
   <tr>
     <th class="vt"><div align="left">Certification:</div></th>
     <td><input name="certification" type="text" id="certification" size="10" maxlength="10"  value="<?php echo $certification;?>"/></td>
     <td>&nbsp;</td>
   </tr>
   <tr>
     <th class="vt"><div align="left">Release Date: </div></th>
     <td><input name="releasedDate" type="text" id="releasedDate" size="11" maxlength="11"  value="<?php echo $releasedDate;?>"/></td>
     <td>&nbsp;</td>
   </tr>
   <tr>
     <th class="vt"><div align="left">Runtime:</div></th>
     <td><input name="runtime" type="text" id="runtime" size="10" maxlength="10"  value="<?php echo $runtime;?>"/></td>
     <td>&nbsp;</td>
   </tr>
   <tr>
     <th class="vt"><div align="left">Budget:</div></th>
     <td><input name="budget" type="text" id="budget" size="20" maxlength="20"  value="<?php echo $budget;?>"/></td>
     <td>&nbsp;</td>
   </tr>
   <tr>
     <th class="vt"><div align="left">Revenue:</div></th>
     <td><input name="revenue" type="text" id="revenue" size="20" maxlength="20"  value="<?php echo $revenue;?>"/></td>
     <td>&nbsp;</td>
   </tr>
   <tr>
     <th class="vt"><div align="left">Director:</div></th>
     <td><input name="director" type="text" id="director" size="50" maxlength="512"  value="<?php echo $director;?>"/></td>
     <td>&nbsp;</td>
   </tr>
   <tr>
     <th class="vt"><div align="left">Video Src: </div></th>
     <td><label>
       <select name="discFlagId" id="discFlagId">
	   <option value="" <?php if($discFlagId == ''){ echo 'selected="selected"';}?>>--None--</option>
	  <?php 
	  	while ($row = mysql_fetch_array($discFlags)) {
	 ?>
	 	<option value="<?php echo $row['id'];?>" <?php if($discFlagId == $row['id']){ echo 'selected="selected"';}?>><?php echo $row['label'];?></option>
	 <?php
	 }
	 ?>
       </select>
     </label></td>
     <td>&nbsp;</td>
   </tr>
   <tr>
     <th class="vt"><div align="left">Audio Src: </div></th>
     <td><label>
       <select name="audioFlagId" id="audioFlagId">
        <option value="" <?php if($audioFlagId == ''){ echo 'selected="selected"';}?>>--None--</option>
	  <?php 
	  	while ($row = mysql_fetch_array($audioFlags)) {
	 ?>
	 	<option value="<?php echo $row['id'];?>" <?php if($audioFlagId == $row['id']){ echo 'selected="selected"';}?>><?php echo $row['label'];?></option>
	 <?php
	 }
	 ?>
       </select>
     </label></td>
     <td>&nbsp;</td>
   </tr>
   <tr>
     <th class="vt"><div align="left">Watched:</div></th>
     <td><label>
       <input name="isWatched" type="checkbox" id="isWatched" value="Y" <?php if($isWatched=='Y'){echo 'checked="checked"';}?>/>
     </label></td>
     <td>&nbsp;</td>
   </tr>
 </tbody></table>
<p>
  <label>
  <input type="submit" name="Submit" value="Save" />
  </label>
  <input type="button" name="cancelButton" value="Cancel" onclick="location='movies-setup.php'"/>
</p>
</form>
<!-- Modal Window Code -->
<div id='confirm'>
	<div class='header'><span>default title</span></div>
	<div id="message" class='message'>
	</div>
	</div>
<!-- preload the images -->
<div style='display:none'>
	<img src='../images/header.gif' alt='' />
</div>
</body>
</html>
